package org.footballmanager.pandafootball.system.controller;

import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.common.util.MD5Encoder;
import org.footballmanager.pandafootball.system.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

public abstract class AddAndEditController<T> extends BaseController {
    @Autowired
    private BaseService<T> baseService;

    /**
     * 抽象方法
     * @return 实体名称
     */
    protected abstract String getEntityName();

    /**
     * 新增记录
     * @param t 实体类
     * @param bindingResult 校验
     * @param request 请求
     * @return 页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@Valid @ModelAttribute T t, BindingResult bindingResult,
                         HttpServletRequest request, SessionStatus s){
        if (!bindingResult.hasErrors()) {
            baseService.save(t, request);
            s.setComplete();
            return String.format(Constants.REDIRECT, Constants.FOOT, getEntityName());
        } else {
            return String.format(Constants.ADDPAGE, Constants.FOOT, getEntityName());
        }
    }

    /**
     * 更新记录
     * @param t 实体类
     * @param bindingResult 校验
     * @param request 请求
     * @return 页面
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute T t, BindingResult bindingResult,
                         HttpServletRequest request, SessionStatus s){
        if (!bindingResult.hasErrors()) {
            baseService.updateNotNull(t, request);
            s.setComplete();
            return String.format(Constants.REDIRECT, Constants.FOOT, getEntityName());
        } else {
            return String.format(Constants.EDITPAGE, Constants.FOOT, getEntityName());
        }
    }
}
